package cn.tedu.csmall.passport.controller; 
 /*
 @Time: 2022/9/7 8:42
 @Author:GShuai
 @File:AdminController.class
 @Software:IntelliJ IDEA
*/

import cn.tedu.csmall.passport.pojo.dto.AdminAddNewDTO;
import cn.tedu.csmall.passport.pojo.dto.AdminLoginDTO;
import cn.tedu.csmall.passport.pojo.vo.AdminListItemVO;
import cn.tedu.csmall.passport.security.LoginPrincipal;
import cn.tedu.csmall.passport.service.IAdminService;
import cn.tedu.csmall.passport.web.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Api(tags = "1. 管理员管理模块")
@RestController
@RequestMapping("/admins")
public class AdminController {
    @Autowired
    private IAdminService adminService;

    public AdminController() {
        log.debug("创建控制器对象：AdminController");
    }

    // http://localhost:9081/admins/add-new
    @ApiOperation("添加管理员")
    @ApiOperationSupport(order = 100)
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    @PostMapping("/add-new")
    public JsonResult addNew(@RequestBody AdminAddNewDTO adminAddNewDTO) {
        log.debug("接收到的请求参数：{}", adminAddNewDTO);
        adminService.addNew(adminAddNewDTO);
        return JsonResult.ok();
    }

    // http://localhost:9081/admins/1/delete
    @ApiOperation("删除管理员")
    @ApiOperationSupport(order = 400)
    @PostMapping("/{id:[0-9]+}/delete")
    @PreAuthorize("hasAuthority('/ams/admin/delete')")
    public JsonResult deleteById(@PathVariable Long id) {
        log.debug("接收到的请求参数：{}", id);
        adminService.deleteById(id);
        return JsonResult.ok();
    }

    // http://localhost:9081/admins/login
    @ApiOperation("管理员登录")
    @ApiOperationSupport(order = 400)
    @PostMapping("/login")
    public JsonResult login(@RequestBody AdminLoginDTO adminLoginDTO) {
        log.debug("接收到的请求参数：{}", adminLoginDTO);
        String jwt = adminService.login(adminLoginDTO);
        return JsonResult.ok(jwt);
    }

    // http://localhost:9081/admins
    @ApiOperation("查询管理员列表")
    @ApiOperationSupport(order = 401)
    @PreAuthorize("hasAuthority('/ams/admin/read')")
    @GetMapping("")
    public JsonResult list(@AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("接收到查询管理员列表的请求");
        log.debug("当前认证信息中的当事人信息：{}", loginPrincipal);
        Long id = loginPrincipal.getId();
        log.debug("从认证信息中获取当前登录的管理员的id：{}", id);
        String username = loginPrincipal.getUsername();
        log.debug("从认证信息中获取当前登录的管理员的用户名：{}", username);
        List<AdminListItemVO> admins = adminService.list();
        return JsonResult.ok(admins);
    }

}
